<template>
  <div>
    <PieChart
      v-loading="loading"
      :key="keyChart"
      :optionData="optionData"
    ></PieChart>
    <div>
      <el-button @click="dataList" type="primary">加载数据</el-button>
    </div>
  </div>
</template>
<script>
import PieChart from "../../components/PieChart.vue";
export default {
  components: {
    PieChart,
  },
  data() {
    return {
      loading: false,
      keyChart: 0,
      optionData: {
        title: "扇形图",
        size: "60%",
        legendData: [],
        seriesName: "类别",
        seriesData: [],
      },
      // 数据格式展示
      legendData2: ["类别一", "类别二", "类别三", "类别四", "类别五"],
      seriesData2: [
        { value: "335", name: "类别一" },
        { value: "310", name: "类别二" },
        { value: "234", name: "类别三" },
        { value: "135", name: "类别四" },
        { value: "1548", name: "类别五" },
      ],
    };
  },
  mounted() {
    this.dataList();
  },
  methods: {
    dataList() {
      this.loading = true;
      // 模拟数据后台请求
      new Promise((r, e) => {
        setTimeout(() => {
          // 模拟后台返回的数据
          let dataList = [
            { name: "类别一", num: "335" },
            { name: "类别二", num: "310" },
            { name: "类别三", num: "234" },
            { name: "类别四", num: "135" },
            { name: "类别五", num: "1548" },
          ];
          r(dataList);
        }, 500);
      }).then((data) => {
        let legendData = [];
        let seriesData = [];
        data.forEach((e) => {
          let obj = {
            name: e.name,
            value: e.num,
          };
          seriesData.push(obj);
          legendData.push(e.name);
        });
        this.optionData.legendData = legendData;
        this.optionData.seriesData = seriesData;
        // 如果遇到加载数据试图没有更新 可在赋值最后添加下面的代码 使用key值强制刷新
        this.keyChart = this.keyChart + 1;
        this.loading = false;
      });
    },
  },
};
</script>